package com.ukao.cashregister.dialog;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.ukao.cashregister.R;
import com.ukao.cashregister.adapter.BatchDialogAdapter;
import com.ukao.cashregister.adapter.DialogBatchDetailsAdapter;
import com.ukao.cashregister.base.BaseDialogFragment;
import com.ukao.cashregister.base.IAdapter;
import com.ukao.cashregister.base.IPage;
import com.ukao.cashregister.base.PageWrapper;
import com.ukao.cashregister.bean.BatchlTabBean;
import com.ukao.cashregister.bean.BatchlistBean;
import com.ukao.cashregister.consts.Constant;
import com.ukao.cashregister.consts.SaveParamets;
import com.ukao.cashregister.eventbus.AppEvent;
import com.ukao.cashregister.listener.MyOnItemClickListener;
import com.ukao.cashregister.retrofit.ApiCallback;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.widget.DividerDecoration;
import com.ukao.cashregister.widget.StateButton;
import com.ukao.cashregister.widget.TwinklingLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 批次对话框
 */

public class BatchDialogFragment extends BaseDialogFragment {


    @BindView(R.id.recycler_view)
    RecyclerView mRecycler;
    @BindView(R.id.twinkling_layout)
    TwinklingLayout twinklingLayout;
    @BindView(R.id.cancel)
    StateButton cancel;
    @BindView(R.id.submit)
    Button submit;
    @BindView(R.id.add_clothing_layout)
    LinearLayout addClothingLayout;

    @BindView(R.id.num_txt)
    TextView numTxt;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.select_txt)
    TextView selectTxt;
    @BindView(R.id.count)
    TextView count;
    private List<BatchlTabBean.ListBean> mData = new ArrayList<>();
    private List<BatchlistBean.ListBean> poiIData = new ArrayList<>();
    private BatchDialogAdapter mBatchDialogAdapter;
    private PageWrapper mPageWrapper;
    private Unbinder unbinder;
    private DialogBatchDetailsAdapter matchDetailsAdapter;
    private String title;
    private String moveBatch;
    private String id;
    private String enterNumber;
    private boolean isMoveALL;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        title = bundle.getString("param1", "");
        id= bundle.getString("param2", ""); /*详情批次过滤自己*/
        isMoveALL= bundle.getBoolean(ARG_PARAM3,false); /*是否是移入全部批次*/
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_batch_fragment, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();


    }


    private void initView() {
        txtTitle.setText(title);
        mRecycler.setLayoutManager(new LinearLayoutManager(activity));
        moveBatch = resources.getString(R.string.move_batch);
        enterNumber= resources.getString(R.string.enter_number);

        if(title.equals(moveBatch)||title.equals(enterNumber)) {/*移动批次*/
            selectTxt.setVisibility(View.GONE);
            numTxt.setVisibility(View.GONE);
            count.setVisibility(View.GONE);
            addClothingLayout.setVisibility(View.GONE);
            mBatchDialogAdapter = new BatchDialogAdapter(activity, mData);
            mRecycler.addItemDecoration(new DividerDecoration(getActivity(), DividerDecoration.VERTICAL_LIST));
            mRecycler.setAdapter(mBatchDialogAdapter);
            mBatchDialogAdapter.setOnItemClickListener(mOnItemClickListener);
        } else { /*添加衣物*/

            matchDetailsAdapter = new DialogBatchDetailsAdapter(activity, poiIData);
            mRecycler.addItemDecoration(new DividerDecoration(getActivity(), DividerDecoration.VERTICAL_LIST));
            mRecycler.setAdapter(matchDetailsAdapter);
            matchDetailsAdapter.setOnItemClickListener(mOnItemClickListener);

        }


        IPage page = new IPage() {

            @Override
            public void load(int geIndex, int pageSize) {
                if(title.equals(moveBatch)||title.equals(enterNumber)) {/*移动批次*/
                    orderProductBatchIn(geIndex, pageSize);

                } else {
                    batchInList(geIndex, pageSize);
                }


            }
        };
        mPageWrapper = new PageWrapper<>(mIAdapter, page);
        twinklingLayout.startRefresh();

    }


    IAdapter mIAdapter = new IAdapter() {
        @Override
        public void setDataSource(List data, boolean isNextLoad) {
            if (title.equals(moveBatch)||title.equals(enterNumber)) {

                mBatchDialogAdapter.setDatas(data);
            } else {
                matchDetailsAdapter.setDatas(data);
            }


            twinklingLayout.finishRefreshing();
            twinklingLayout.setEnableLoadmore(isNextLoad);


        }

        @Override
        public void loadMoreFinish(List data, boolean isNextLoad) {
            if (title.equals(moveBatch)||title.equals(enterNumber)) {

                mBatchDialogAdapter.addDatas(data);
            } else {
                matchDetailsAdapter.addDatas(data);
            }

            twinklingLayout.finishLoadmore();
            twinklingLayout.setEnableLoadmore(isNextLoad);

        }
    };

    @Override
    protected void initListener() {
        super.initListener();


        twinklingLayout.setOnRefreshListener(mRefreshListenerAdapter);
    }


    private MyOnItemClickListener mOnItemClickListener = new MyOnItemClickListener() {
        @Override
        public void onItemClick(ViewGroup viewGroup, View view, Object o, int i) {

            if (title.equals(moveBatch)||title.equals(enterNumber)) {
                BatchlTabBean.ListBean item = (BatchlTabBean.ListBean) o;
                if (item.isCheck()) return;
                item.setCheck(!item.isCheck());
                for (int j = 0; j < mData.size(); j++) {
                    if (i != j) {
                        mData.get(j).setCheck(false);
                    }
                }
                mBatchDialogAdapter.notifyDataSetChanged();

            } else {
                BatchlistBean.ListBean item = (BatchlistBean.ListBean) o;
                item.setCheck(!item.isCheck());
                int count = 0;
                for (BatchlistBean.ListBean mDataBean  : poiIData) {
                    if (mDataBean.isCheck()) {
                        count = count + 1;
                    }

                }
                numTxt.setText(count + "");
                matchDetailsAdapter.notifyDataSetChanged();

            }
        }


    };

    private RefreshListenerAdapter mRefreshListenerAdapter = new RefreshListenerAdapter() {
        @Override
        public void onRefresh(TwinklingRefreshLayout refreshLayout) {
            super.onRefresh(refreshLayout);

            mPageWrapper.loadPage(true);
        }

        @Override
        public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
            super.onLoadMore(refreshLayout);

            mPageWrapper.loadPage(false);

        }
    };
    /**
     送厂tab 列表
     */
    public void orderProductBatchIn(int pageNum, int pageSize) {
        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("pageNum", pageNum + "");
        mHashMap.put("pageSize", pageSize + "");
        mHashMap.put("isFinish","0");/*1是完成0未完成*/
        mHashMap.put("accessToken", SaveParamets.getToken(activity));
        addSubscription(apiStores().orderProductBatchIn(Constant.createParameter(mHashMap)),
                new ApiCallback<BatchlTabBean>() {
                    @Override
                    public void onSuccess(BatchlTabBean model) {

                        if (model.getHttpCode() == 200) {
                            List<BatchlTabBean.ListBean> mMoveData = model.getData().getList();
                            for (int i = 0; i < mMoveData.size(); i++) {
                                if (mMoveData.get(i).getId().equals(id)){
                                    mMoveData.remove(i);

                                }
                            }

                            mPageWrapper.addDataSource(mMoveData, model.getData().getPages());

                        } else {
                            T.show(model.getMsg());

                        }
                    }


                    @Override
                    public void onFinish() {

                    }
                });
    }


    public void batchInList(int pageNum, int pageSize) {

        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("pageNum", pageNum + "");
        mHashMap.put("pageSize", pageSize + "");
        mHashMap.put("accessToken", SaveParamets.getToken(activity));
        addSubscription(apiStores().batchInList(Constant.createParameter(mHashMap)),
                new ApiCallback<BatchlistBean>() {
                    @Override
                    public void onSuccess(BatchlistBean model) {

                        if (model.getHttpCode() == 200) {

                            mPageWrapper.addDataSource(model.getData().getList(), model.getData().getPages());


                        } else {
                            T.show(model.getMsg());

                        }
                    }


                    @Override
                    public void onFinish() {

                    }
                });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.cancel, R.id.submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cancel:
                dismiss();
                break;
            case R.id.submit:
                if(title.equals(moveBatch)||title.equals(enterNumber)) {  /*移动批次*/
                 String   moveId="";
                    for (int i = 0; i < mData.size(); i++) {

                       if (mData.get(i).isCheck())
                        moveId=mData.get(i).getId();
                    }
                    if (moveId.isEmpty())return;
                    if (isMoveALL){
                        AppEvent.postHasData(AppEvent.Message.allMovebatch,moveId);
                    }else{
                        AppEvent.postHasData(AppEvent.Message.movebatch,moveId);
                    }
                    dismiss();
                }else{
                    String   addId="";
                    for (int i = 0; i < matchDetailsAdapter.getDatas().size(); i++) {
                        if (matchDetailsAdapter.getDatas().get(i).isCheck())
                        addId=addId+matchDetailsAdapter.getDatas().get(i).getId()+",";
                    }
                    if (addId.isEmpty())return;
                    addId=addId.substring(0,addId.length()-1);
                    AppEvent.postHasData(AppEvent.Message.addbatch,addId);
                    dismiss();
                }


                break;
        }
    }
}
